package problems.solved;

import problems.Problem;

public class Problem112 extends Problem<Integer> {
	public static void main(String[] args) {
		Problem112 problem112 = new Problem112();
		problem112.runTimed();
		problem112.printResult();
	}

	@Override
	public void run() {
		int bouncy = 0;
		for (int i = 101; ; i++) {
			if (isBouncy(i)) bouncy++;
			if (i - bouncy == i / 100) {
				setResult(i); // 1587000
				return;
			}
		}
	}

	private boolean isBouncy(int n) {
		String string = Integer.toString(n);
		int i = 0;
		while (i < string.length()-1 && sameStartChar(string, i)) {
			i++;
		}
		
		if (i == string.length()-1) {
			return false;
		}
		
		return string.charAt(i) < string.charAt(i + 1) ? !isAscending(string.substring(i)) : !isDescending(string.substring(i));
	}

	private boolean sameStartChar(String string, int i) {
		return string.charAt(i) == string.charAt(i+1);
	}

	private boolean isDescending(String string) {
		char prev = '9';
		int i = 0;
		while (i < string.length()) {
			if (string.charAt(i++) <= prev) {
				prev = string.charAt(i-1);
			}
			else {
				return false;
			}
		}
		return true;
	}

	private boolean isAscending(String string) {
		char prev = '0';
		int i = 0;
		while (i < string.length()) {
			if (string.charAt(i++) >= prev) {
				prev = string.charAt(i-1);
			}
			else {
				return false;
			}
		}
		return true;
	}
}
